package com.medical.controller;


import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;


import com.google.zxing.WriterException;
import com.medical.entity.Conference;
import com.medical.entity.Convention;
import com.medical.entity.MyException;
import com.medical.entity.Refund;
import com.medical.entity.ResultBean;
import com.medical.entity.TeacherOrder;
import com.medical.entity.User;
import com.medical.service.RefundService;
import com.medical.service.TeacherOrderService;
import com.medical.service.UserService;
import com.medical.util.QRcodeUtil;
import com.medical.util.WxPayUtil;
import com.medical.websocket.TextMessageHandler;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/teacherOrder")
@Api(description="订单操作")
public class TeacherOrderController {
	@Autowired
	private TeacherOrderService biz;
	
	@Autowired
	private UserService uBiz;
	
	@Autowired
	private RefundService rBiz;
	
	@Autowired
	TextMessageHandler handler;
	
	
	@PostMapping("/getOrderList")
	@ApiOperation(value ="查询翻译订单列表", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "merchantid", value = "翻译用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states", value = "订单状态1待确认2进行中3待退款4已完成5取消退款", required = false, dataType = "int")
	})
	public ResultBean<List<Map<String, Object>>> getOrderList(int merchantid,int states){
		return biz.getOrderList(merchantid, states);
	}
	
	@PostMapping("/getOrderListCount")
	@ApiOperation(value ="PC查询翻译订单列表", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "merchantid", value = "翻译用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states", value = "订单状态1待确认2进行中3待退款4已完成5取消退款", required = false, dataType = "int"),
		@ApiImplicitParam(name = "pageIndex", value = "当前页数", required = false, dataType = "int"),
		@ApiImplicitParam(name = "size", value = "每页条数", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> getOrderListCount(int merchantid,int states,int pageIndex,int size){
		return biz.getOrderListCount(merchantid, states, pageIndex, size);
	}
	
	
	@PostMapping("/getByOrderId")
	@ApiOperation(value ="查询订单详情", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "typeId", value = "查询订单列表中type字段，1 老师 2译员 3直播课 4线下课 5视听课 6签证 7会议 8会展9单节课", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> getByOrderId(int typeId,int orderId){
		return biz.getByOrderId(typeId, orderId);
	}
	
	/**
	 * 用户订单列表查询
	 * @param typeId
	 * @param orderId
	 * @return
	 */
	@PostMapping("/findOrderForUsers")
	@ApiOperation(value ="查询用户订单列表", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states 1待付款 2待确认 3进行中 4待评价 5已完成 6取消退款", value = "订单状态", required = false, dataType = "int")
	})
	public  ResultBean<List<Map<String, Object>>> findOrdersForUsers(int userid,int states){
		return biz.findOrdersForUsers(userid, states);
	}
	
	/**
	 * 用户订单列表查询
	 * @param typeId
	 * @param orderId
	 * @return
	 */
	@PostMapping("/findOrderForUsersCount")
	@ApiOperation(value ="PC查询用户订单列表总条数", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states 1待付款 2待确认 3进行中 4待评价 5已完成 6取消退款", value = "订单状态", required = false, dataType = "int")
	})
	public  ResultBean<Integer> findOrderForUsersCount(int userid,int states){
		return biz.findOrderForUsersCount(userid, states);
	}
	
	/**
	 * 取消订单
	 * @param orderId
	 * @param orderType
	 * @return
	 */
	@PostMapping("/cancelOrder")
	@ApiOperation(value ="取消订单", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> cancelOrder(int orderId,int orderType){
		ResultBean<Map<String, Object>> result=biz.updateOrderState(orderType, orderId, 6,0);
		return result;
	}
	/**
	 * 确认付款
	 * @param orderId
	 * @param orderType
	 * @return
	 */
	@PostMapping("/confirmPayment")
	@ApiOperation(value ="确认付款", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "paytype", value = "支付方式 1微信支付 2支付宝 3余额支付", required = false, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "integral", value = "获得积分数", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> confirmPayment(int orderId,int orderType,int paytype,int userId,int integral){
		ResultBean<Map<String, Object>> result=biz.updateOrderState(orderType, orderId, 3,paytype);
		uBiz.updateIntegral(integral, userId,false);
		Map<String, Object> map=result.getData();
		String price="";
		
		int merchantid=0;
		if(map.get("merchantid")!=null) {
			merchantid=Integer.parseInt(map.get("merchantid").toString());
			price=map.get("totalprice").toString();
		}else {
			if(orderType==3||orderType==4||orderType==5) {
				merchantid=Integer.parseInt(map.get("shangId").toString());
				price=map.get("totalprice").toString();
			}else if(orderType==7) {
				Conference cf=(Conference) map.get("conference");
				merchantid=cf.getUserid();
				price=cf.getPrice().toString();
			}else if(orderType==8) {
				Convention cf=(Convention) map.get("convention");
				merchantid=cf.getUserid();
				price=cf.getPrice().toString();
			}
		}
		Double money=Double.valueOf(price);
		biz.addConsumption(userId, money, "微信支付付款");
		if(paytype==3) {
			int userid=Integer.parseInt(map.get("userid").toString());
			User user=uBiz.getByUserId(userid);
			money=user.getBalance()-money;
			user.setBalance(money);
			uBiz.updateUsers(user);
		}
		
		User merchant=uBiz.getByUserId(merchantid);
		Double money1=Double.valueOf(price);
		biz.addConsumption(merchantid, money1, "微信支付收款");
		money1=merchant.getBalance()+money1;
		merchant.setBalance(money1);
		uBiz.updateUsers(merchant);
		return result;
	}
	
	/**
	 * 更改订单状态
	 * @param orderId
	 * @param orderType
	 * @return
	 */
	@PostMapping("/editStates")
	@ApiOperation(value ="更改订单状态", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states", value = "订单状态 1未支付未确认 2未支付已确认  3已支付已确认 4待退款 5已退款 6已取消 7已完成未评价  8已投诉 9已完成已评价 10拒绝退款 11用户删除 12商家删除", required = false, dataType = "int"),
	})
	public ResultBean<Map<String, Object>> editStates(int orderId,int orderType,int states){
		ResultBean<Map<String, Object>> result=biz.updateOrderState(orderType, orderId, states,0);
		return result;
	}
	
	/**
	 * 申请退款
	 * @param orderId
	 * @param orderType
	 * @return
	 */
	@PostMapping("/resund")
	@ApiOperation(value ="申请退款", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "reason", value = "退款理由", required = false, dataType = "string")
	})
	public ResultBean<Map<String, Object>> resund(int orderId,int orderType,int userId,String reason){
		Refund refund=new Refund();
		refund.setOrderid(orderId);
		refund.setOrdertype(orderType);
		refund.setUserid(userId);
		refund.setStates(1);
		refund.setTime(new Date());
		refund.setReason(reason);
		rBiz.addRefund(refund);
		ResultBean<Map<String, Object>> result=biz.updateOrderState(orderType, orderId, 4,0);
		return result;
	}
	
	@PostMapping("/refuse")
	@ApiOperation(value ="拒绝退款", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "refuse", value = "拒绝理由", required = false, dataType = "string")
	})
	public ResultBean<Map<String, Object>> refuse(int orderId,int orderType,int userId,String refuse){
		try {
			Refund refund=new Refund();
			refund.setOrderid(orderId);
			refund.setOrdertype(orderType);
			refund.setUserid(userId);
			refund=rBiz.getByOrderId(refund);
			refund.setStates(3);
			refund.setRefuse(refuse);
			rBiz.updateStates(refund);
			ResultBean<Map<String, Object>> result=biz.updateOrderState(orderType, orderId, 10,0);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}
	
	@PostMapping("/agreeResund")
	@ApiOperation(value ="同意退款", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "orderType", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> agreeResund(int orderId,int orderType,int userId){
		try {
			ResultBean<Map<String, Object>> result=biz.getByOrderId(orderType, orderId);
			Map<String, Object> map=result.getData();
			String orderNo=map.get("ordernumber").toString();
			String price=map.get("totalprice").toString();
			int paytype=Integer.parseInt(map.get("paytype").toString());
			Boolean pan=false;
			int merchantid=0;
			Double money1=Double.valueOf(price);
			if(map.get("merchantid")!=null) {
				merchantid=Integer.parseInt(map.get("merchantid").toString());
			}else {
				if(orderType==3||orderType==4||orderType==5) {
					merchantid=Integer.parseInt(map.get("shangId").toString());
				}
			}
			if(paytype==1) {
				pan=WxPayUtil.refund(orderNo, price, price);
			}else {
				
				User user=uBiz.getByUserId(userId);
				Double money=Double.valueOf(price);
				money=money+user.getBalance();
				user.setBalance(money);
				int count=uBiz.updateUsers(user);
				if(count>0) {
					pan=true;
				}
			}
			User merchant=uBiz.getByUserId(merchantid);
			money1=merchant.getBalance()-money1;
			merchant.setBalance(money1);
			uBiz.updateUsers(merchant);
			if(pan) {
				Refund refund=new Refund();
				refund.setOrderid(orderId);
				refund.setOrdertype(orderType);
				refund.setUserid(userId);
				refund.setStates(2);
				rBiz.updateStates(refund);
				result=biz.updateOrderState(orderType, orderId, 5,0);
				return result;
			}else {
				return new ResultBean<>(new MyException("退款失败"));
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(new MyException(e.getMessage()));
		}
	}
	
	@PostMapping("/addOrder")
	@ApiOperation(value ="添加订单", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "ordernumber", value = "订单号（时间戳生成）", required = false, dataType = "string"),
		@ApiImplicitParam(name = "num", value = "购买数量", required = false, dataType = "int"),
		@ApiImplicitParam(name = "phone", value = "预约电话", required = false, dataType = "string"),
		@ApiImplicitParam(name = "attendtime", value = "上课时间", required = false, dataType = "date"),
		@ApiImplicitParam(name = "chargetype", value = "收费类型", required = false, dataType = "string"),
		@ApiImplicitParam(name = "address", value = "上课地点", required = false, dataType = "string"),
		@ApiImplicitParam(name = "remark", value = "备注", required = false, dataType = "String"),
		@ApiImplicitParam(name = "totalprice", value = "总价", required = false, dataType = "double"),
		@ApiImplicitParam(name = "userid", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "paytype", value = "支付方式", required = false, dataType = "int"),
		@ApiImplicitParam(name = "merchantid", value = "商家userid", required = false, dataType = "int"),
		@ApiImplicitParam(name = "teacherid", value = "发布老师id", required = false, dataType = "int")
	})
	public ResultBean<TeacherOrder> addOrder(TeacherOrder to){
		return biz.addOrder(to);
	}
	
	@PostMapping("/payer")
	@ApiOperation(value ="支付", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "money", value = "价格", required = false, dataType = "Double"),
		@ApiImplicitParam(name = "ordernum", value = "订单号", required = false, dataType = "String")
	})
	public Map<String, Object> createUnifiedOrder(@RequestParam("userId") int userId, @RequestParam("money") String money,  HttpServletRequest request, HttpServletResponse response,String ordernum) {
		try {
			User user = uBiz.getByUserId(userId);
			return WxPayUtil.createUnifiedOrder(money, user.getOpenid(), "鸟语网", userId, ordernum, response, request);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@RequestMapping("/payCallback")
	public void payCallback(HttpServletRequest request, HttpServletResponse response) {
		WxPayUtil.payCallback(request, response);
	}
	
	@RequestMapping("/QRpayCallback")
	public void QRpayCallback(HttpServletRequest request, HttpServletResponse response) {
		String order=WxPayUtil.QRpayCallback(request, response);
		TextMessage message = new TextMessage("QR,"+order);
		handler.sendMessageToUsers(message);
	}
	
	@PostMapping("/yuePay")
	@ApiOperation(value ="订单余额支付", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", value = "订单id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "type", value = "订单类型1老师 2译员 3直播课4线下课5视听课6签证7会议8会展", required = false, dataType = "int"),
		@ApiImplicitParam(name = "states", value = "订单状态 1未支付未确认 2未支付已确认  3已支付已确认 4待退款 5已退款 6已取消 7已完成未评价  8已投诉 9已完成已评价", required = false, dataType = "int"),
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "money", value = "价格", required = false, dataType = "Double"),
		@ApiImplicitParam(name = "integral", value = "获得积分数", required = false, dataType = "int")
	})
	public ResultBean<Map<String, Object>> yuePay(int type,int orderId,int states,int userId,Double money,int integral){
		User user=uBiz.getByUserId(userId);
		if(user.getBalance()>=money) {
		
		 ResultBean<Map<String, Object>> result=biz.getByOrderId(type, orderId);
		 Map<String, Object> map=result.getData();
			Double money1=money;
			int merchantid=0;
			if(map.get("merchantid")!=null) {
				merchantid=Integer.parseInt(map.get("merchantid").toString());
			}else {
				if(type==3||type==4||type==5) {
					merchantid=Integer.parseInt(map.get("shangId").toString());
				}
			}
			User merchant=uBiz.getByUserId(merchantid);
			
			biz.yuePay(type, orderId, states, userId, money,merchantid,money1);
			uBiz.updateIntegral(integral, userId,false);
			
			//money=user.getBalance()-money;
			//user.setBalance(money);
			//uBiz.updateUsers(user);
			money1=merchant.getBalance()+money1;
			merchant.setBalance(money1);
			
			uBiz.updateUsers(merchant);
		 return result;
		}else {
			return new ResultBean<>(new MyException("余额不足"));
		}
	}
	
	@GetMapping("/qrPay")
	@ApiOperation(value ="扫码支付", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int"),
		@ApiImplicitParam(name = "money", value = "价格", required = false, dataType = "Double"),
		@ApiImplicitParam(name = "ordernum", value = "订单号", required = false, dataType = "String")
	})
	public void qrPay(@RequestParam("userId") int userId, @RequestParam("money") String money,  HttpServletRequest request, HttpServletResponse response,String ordernum) throws WriterException, IOException {
		try {
			Map<String, String> map=WxPayUtil.QRcode(money, "鸟语网", userId, ordernum, response, request);
			if(map!=null) {
				String code_url=map.get("code_url");
				QRcodeUtil.encodeQrcode(code_url,response);
			}
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
